package org.smardi.fakeCall.Timer;

import java.text.*;
import java.util.*;

import org.smardi.fakeCall.*;
import org.smardi.fakeCall.R.*;
import org.smardi.fakeCall.Service.*;
import org.smardi.fakeCall.Setting.*;

import android.app.*;
import android.app.AlertDialog.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;

public class AC_Timer extends Activity {

	boolean D = false;
	String TAG = "FakeCall";

	TextView btn_top_left = null;
	
	CheckBox cbox_timer = null;
	
	TextView txt_nowTime = null;
	TextView txt_targetTime = null;

	Button btn_5sec = null;
	Button btn_30sec = null;
	Button btn_1min = null;
	Button btn_3min = null;
	Button btn_5min = null;
	Button btn_10min = null;
	Button btn_time_custom = null;
	
	Button btn_apply = null;
	
	ArrayList<Button> listTimeSetButton = new ArrayList<Button>();

	private final int WHAT_NOW_TIME = 0;

	long time_now = 0; // 화면에 표시되는 현재 시간
	long time_increase = 0; // 목표시간과 현재시간의 차이
	long time_target = 0; // 화면에 표시되는 목표 시간

	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("(M/d) a hh:mm:ss");

	SharedPreference_FakeCall mPref = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_timer);

		mPref = new SharedPreference_FakeCall(AC_Timer.this);
		
		initComponent();

		nowTimeThread.start();
	}

	private void initComponent() {
		btn_top_left = (TextView) findViewById(R.id.btn_top_left);

		cbox_timer = (CheckBox)findViewById(R.id.cbox_timer);
		
		txt_nowTime = (TextView) findViewById(R.id.txt_nowTime);
		txt_targetTime = (TextView) findViewById(R.id.txt_targetTime);

		btn_5sec = (Button) findViewById(R.id.btn_5sec);
		btn_30sec = (Button) findViewById(R.id.btn_30sec);
		btn_1min = (Button) findViewById(R.id.btn_1min);
		btn_3min = (Button) findViewById(R.id.btn_3min);
		btn_5min = (Button) findViewById(R.id.btn_5min);
		btn_10min = (Button) findViewById(R.id.btn_10min);
		btn_time_custom = (Button) findViewById(R.id.btn_time_custom);
		
		btn_apply = (Button)findViewById(R.id.btn_apply);

		listTimeSetButton.add(btn_5sec);
		listTimeSetButton.add(btn_30sec);
		listTimeSetButton.add(btn_1min);
		listTimeSetButton.add(btn_3min);
		listTimeSetButton.add(btn_5min);
		listTimeSetButton.add(btn_10min);
		listTimeSetButton.add(btn_time_custom);

		time_target = mPref.getTargetTime();
		setTimeState();

		registEvent();
	}

	private void registEvent() {
		btn_top_left.setOnClickListener(viewOnClick);

		cbox_timer.setOnClickListener(viewOnClick);
		
		btn_5sec.setOnClickListener(viewOnClick);
		btn_30sec.setOnClickListener(viewOnClick);
		btn_1min.setOnClickListener(viewOnClick);
		btn_3min.setOnClickListener(viewOnClick);
		btn_5min.setOnClickListener(viewOnClick);
		btn_10min.setOnClickListener(viewOnClick);
		btn_time_custom.setOnClickListener(viewOnClick);
		
		btn_apply.setOnClickListener(viewOnClick);
	}

	View.OnClickListener viewOnClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_top_left:
				exit();
				break;
				//-------------------------------------------
			case R.id.cbox_timer:
				if(cbox_timer.isChecked() == false) {
					setCheckbox(false);
					time_target = 0;
					time_increase = 0;
					txt_targetTime.setText("정해지지 않았음");
					toggleTimeSettingButton(-1);
				}
				break;
				//-------------------------------------------
			case R.id.btn_5sec:
				time_increase = 5 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_30sec:
				time_increase = 30 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_1min:
				time_increase = 60 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_3min:
				time_increase = 3 * 60 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_5min:
				time_increase = 5 * 60 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_10min:
				time_increase = 10 * 60 * 1000;
				setTimeState();
				toggleTimeSettingButton(v.getId());
				break;
			case R.id.btn_time_custom:
				TimePickerDialog timePickerDialog = null;
				Date date = null;
				if (time_target < time_now) {
					date = new Date(time_now);
				} else {
					date = new Date(time_target);
				}

				timePickerDialog = new TimePickerDialog(AC_Timer.this,
						timeListener, date.getHours(), date.getMinutes(), false);
				timePickerDialog.show();
				break;
			//-------------------------------------------
			case R.id.btn_apply:
				apply();
				break;
			}
		}
	};

	
	/**
	 * 설정된 시간을 적용하고 빠져나간다.
	 */
	private void apply() {
		
		if(0 < time_target) {
			//Notification 
			Intent intent = new Intent();
			intent.setAction(SV_FakeCall.ACTION_FAKECALL_NOTIFICATION_TIMER);
			intent.putExtra("time_target", time_target);
			mPref.setTargetTime(time_target);
			sendBroadcast(intent);
		} else {
			Intent intentCancel = new Intent();
			intentCancel.setAction(SV_FakeCall.ACTION_FAKECALL_TIMER_CANCEL);
			mPref.setTargetTime(time_target);
			sendBroadcast(intentCancel);
		}
		finish();
	}
	
	/**
	 * 설정된 시간을 적용하지 않고 빠져나간다
	 */
	private void exit() {
		if(time_target > 0) {
			AlertDialog.Builder alert = new AlertDialog.Builder(AC_Timer.this);
			alert.setTitle("나가기");
			alert.setMessage("설정하지 않고 나가시겠습니까?");
			alert.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			alert.show();
		} else {
			finish();
		}
	}
	
	/**
	 * 시간을 설정하는 버튼이 클릭되면 그 버튼을 토글시킨다
	 * @param id 버튼의 아이디
	 */
	private void toggleTimeSettingButton(int id) {
		for (int i = 0; i < listTimeSetButton.size(); i++) {

			Button button = listTimeSetButton.get(i);

			if (button.getId() == id) {
				button.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.button_1));
			} else {
				button.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.c_button));
			}
		}
		
		if(id > -1) {
			setCheckbox(true);
		}
	}
	
	/**
	 * 타이머가 켜져있음을 나타내는 체크박스를 체크하거나 해제한다.
	 * 
	 * @param checked 체크박스를 설정하려는 상태
	 */
	private void setCheckbox(boolean checked) {
		cbox_timer.setChecked(checked);
		
		if(checked == false) {
			cbox_timer.setEnabled(false);
			cbox_timer.setVisibility(View.INVISIBLE);
		} else {
			cbox_timer.setEnabled(true);
			cbox_timer.setVisibility(View.VISIBLE);
		}
		
		if(D) {
			Log.i(TAG, "checked:"+checked);
			Log.i(TAG, "cbox_timer.isChecked():"+cbox_timer.isChecked());
			Log.i(TAG, "cbox_timer.isEnabled():"+cbox_timer.isEnabled());
			Log.e(TAG, "--------------");
		}
	}

	private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			Date nowDate = new Date(time_now);
			Date selectedDate = new Date(nowDate.getYear(), nowDate.getMonth(),
					nowDate.getDate(), hourOfDay, minute);

			if (selectedDate.getTime() < nowDate.getTime()) {
				selectedDate = new Date(selectedDate.getTime() + 24 * 60 * 60
						* 1000);
			}

			setTargetTime(selectedDate.getTime());
			toggleTimeSettingButton(R.id.btn_time_custom);
		}
	};

	/**
	 * 현재 시간 및 목표시간을 즉시 표시한다
	 */
	private void setTimeState() {
		
		time_now = new Date().getTime();
		txt_nowTime.setText(simpleDateFormat.format(new Date()));

		if (time_increase > 0) {
			time_target = (long) (time_now + time_increase);
			txt_targetTime.setText(simpleDateFormat
					.format(new Date(time_target)));
		}
		
		if(0 < time_target) {
			txt_targetTime.setText(simpleDateFormat
					.format(new Date(time_target)));
			setCheckbox(true);
		} else {
			setCheckbox(false);
		}
		
		
		if (D) {
			Log.e(TAG, "--------------------------");
			Log.i(TAG, "Now Date().getTime():" + time_now);
			Log.i(TAG, "Increase time:" + time_increase);
			Log.i(TAG, "Target time:" + time_target);
		}
	}

	private void setTargetTime(long time) {
		time_increase = 0;
		time_target = time;
		txt_targetTime.setText(simpleDateFormat.format(new Date(time)));
	}

	// Handler
	Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {

			switch (msg.what) {
			case WHAT_NOW_TIME:

				setTimeState();
				break;
			}

			return false;
		}
	});

	// --------------------------------------------------
	// 현재 시간을 표시하기 위한 스레드
	Thread nowTimeThread = new Thread(new Runnable() {

		long oldTime = 0;

		@Override
		public void run() {

			while (true) {

				Date time = new Date();

				if (time.getTime() % 1000 < 50 && 950 < time.getTime() - oldTime) {
					time_now = time.getTime();

					Message msg = new Message();
					msg.what = WHAT_NOW_TIME;
					mHandler.sendMessage(msg);
					oldTime = time_now;

					
				}
				
				try {
					Thread.sleep(40);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	});
}
